/*
 * @Author: chunlai
 * @Date: 2023-07-25 09:48:14
 * @LastEditTime: 2025-09-01 15:12:26
 * @LastEditors: minsheng_insurance_agency_zhoucl
 * @FilePath: \02.bldinsure\src\store\modules\risks.js
 * @Description:
 */

import { Dialog } from "vant";
import { validRules } from "@/translate/risks/rules";
import { GetToRateparams } from "@/translate/risks/rate";
import { apiGetRate } from "@/utils/functions";
import { getCacheValue } from "@/methods/cache.js";

const state = [];
const getters = {
  mainInsu: (state) => {
    return state.filter((todo) => todo.ismain);
  },
  subRisk: (state) => {
    return state.filter((todo) => !todo.ismain);
  },
  showedRisks: (state) => {
    return state.filter((todo) => todo.ismain || todo.checked);
  },
  allRisk: (state) => {
    return state;
  },
  fanXiQianFlag: (state, getters, rootState) => {
    let res = false;
    if (rootState.page.fxqCount == "1") {
      const risks = JSON.parse(JSON.stringify(getters.showedRisks)),
        len = risks.length;
      let mi = 0;
      for (let m = 0; m < len; m++) {
        const item = risks[m],
          year = item.payendyear == "趸交" ? 1 : item.payendyear,
          payFee = item.prem * year;
        mi = (payFee + mi).toFixed(2) * 1;
      }
      if (mi > 200000) {
        res = true;
      }
    }
    return res;
  },
};
const mutations = {
  // 险种字段赋值
  SET_RISKSTATE(state, data) {
    if (data) {
      for (let i = 0; i < data.length; i++) {
        state[i] = data[i];
      }
    }
  },
  UPDATE_RISKCODE(state, payload) {
    const len = state.length;
    for (let r = 0; r < len; r++) {
      const item = state[r];
      if (item.varietyCode == payload.varietyCode) {
        state[r][payload.keyName] = payload.keyValue;
      }
    }
    state = state.splice(1, 0);
  },
  UPDATE_MAIN_ITEM(state, data) {
    Object.assign(state[0], data);
    state = state.splice(1, 0);
  },
  /**
   * 试算接口返回数据: 回显保费
   * @param {*} state
   * @param {*} data
   */
  SET_RISKRATE(state, data) {
    // console.log('试算:', data);
    // 校验输入参数
    if (!Array.isArray(state) || !Array.isArray(data)) {
      console.error("Invalid input parameters");
      return;
    }
    const gysName = getCacheValue("insert", "compEngName");
    // 创建一个哈希表用于快速查找
    const dataMap = new Map();
    for (let item of data) {
      dataMap.set(item.varietyCode, item);
    }
    for (let i = 0; i < state.length; i++) {
      const varietyCode = state[i].varietyCode;
      if (dataMap.has(varietyCode)) {
        const dataItem = dataMap.get(varietyCode);
        state[i].prem = dataItem.prem;
        state[i].amnt = dataItem.amnt;
        if (!["ansheng"].includes(gysName)) {
          state[i].planCode = dataItem.planCode;
        }
        // 责任回显(liabilityList >>> dutyList: 长城00536)
        if (dataItem.premDutyList && dataItem.premDutyList.length > 0) {
          if (state[i].liabilityList) {
            state[i].liabilityList.forEach((e) => {
              const fdObj2 = dataItem.premDutyList.find(
                (dty) => dty.dutyCode == e.dutyCode
              );
              if (fdObj2) {
                e.prem = fdObj2.prem;
                e.amnt = fdObj2.amnt;
              }
            });
          }
          if (state[i].duty3List) {
            state[i].duty3List.forEach((e) => {
              const fd3Obj = dataItem.premDutyList.find((dty) => {
                const fd61 = e.options.find(
                  (fd61) => fd61.value == dty.dutyCode
                );
                return fd61 ? dty : null;
              });
              if (fd3Obj) {
                e.value = fd3Obj.dutyCode;
                e.isChecked = true;
                e.prem = fd3Obj.prem;
                e.amnt = fd3Obj.amnt;
              }
            });
          }
          if (state[i].planPushDtys) {
            if (state[i].planPushDtys == "1") {
              const fdPdty = dataItem.premDutyList.find(
                (pdt) => pdt.dutyCode == state[i].planCode
              );
              if (fdPdty) {
                let obj3 = {
                  dutyCode: fdPdty.dutyCode || "",
                  dutyAmnt: fdPdty.amnt || "",
                  dutyPrem: fdPdty.prem || "",
                };
                // 新加计划责任数据字段
                state[i].planDutyObj = obj3;
              }
            }
          }
        }
        if (dataItem.dutyList && dataItem.dutyList.length > 0) {
          state[i].dutyDescList = dataItem.dutyList;
        }
      }
    }
    state = state.splice(1, 0);
  },
  // 数据库险种信息(translate\risks\insert.js GetRiskData预处理) >>> store回显
  SET_RISKS_DATA(state, data) {
    // 检查输入的有效性
    if (!Array.isArray(data) || !Array.isArray(state)) {
      console.error("Invalid input: data or state is not an array");
      return;
    }
    const data2Map = new Map();
    data.forEach((item) => {
      if (item.varietyCode) {
        data2Map.set(item.varietyCode, item);
      }
    });
    // console.log('SET_RISKS_DATA', data);
    for (let i = 0; i < state.length; i++) {
      const data2Item = data2Map.get(state[i].varietyCode);
      if (data2Item) {
        [
          "prem",
          "amnt",
          "insuYear",
          "payendyear",
          "checked",
          "renewFlag",
          "planCode",
        ].forEach((key) => {
          if (data2Item[key] !== undefined) {
            state[i][key] = data2Item[key];
            if (key === "planCode") {
              if (state[i].planSubName !== void 0) {
                const plan0Tag = state[i].plansArr.find(
                  (p0) => p0.value == state[i].planCode
                );
                if (plan0Tag) {
                  state[i].planSubName = plan0Tag.subName;
                }
              }
            }
          }
        });

        if (
          data2Item.insuYear &&
          state[i].insureYearList &&
          state[i].insureYearList.length > 0
        ) {
          state[i].insuYear = data2Item.insuYear;
        }
        state[i].mult = data2Item.mult || "1";
        if (data2Item.planCode !== void 0) {
          state[i].planCode = data2Item.planCode;
          if (state[i].dutyList !== void 0) {
            // 可选责任转化的
            let duty3s = state[i].dutyList;
            const tranObj = state[i].jibenTrans;
            for (let key in tranObj) {
              if (tranObj[key] == data2Item.planCode) {
                // baseDutyCode 默认为基本责任1,与其他可选的拼接,再转化为planCode
                // dutyCode 后面险种table表格显示文字描述直接取值
                if (state[i].dutyCode) {
                  state[i].dutyCode = `${key}`;
                }
                duty3s.forEach((tagDut) => {
                  if (key.indexOf(tagDut.value) > 0) {
                    tagDut.isCheck = true;
                  }
                  if (tagDut.radioOptions && tagDut.radioOptions.length > 0) {
                    const fd2 = tagDut.radioOptions.find(
                      (rd) => key.indexOf(rd.value) > 0
                    );
                    if (fd2) {
                      tagDut.value = fd2.value;
                      tagDut.isCheck = true;
                    } else {
                      tagDut.value = "0";
                      tagDut.isCheck = false;
                    }
                  }
                });
              }
            }
            state[i].dutyList = JSON.parse(JSON.stringify(duty3s));
          }
        }
        // 可选责任列表 --- 类型2回显数据(liabilityList >>> list)
        if (data2Item.dutys && data2Item.dutys.length > 0) {
          if (state[i].liabilityList) {
            state[i].liabilityList.forEach((e) => {
              // 长城(00536)
              data2Item.dutys.forEach((dut) => {
                if (dut.dutyCode == e.dutyCode) {
                  // console.log(dut.dutyCode);
                  e.prem = dut.dutyPrem;
                  e.amnt = dut.dutyAmnt;
                  e.isChecked = true;
                }
              });
            });
          }
          if (state[i].duty3List) {
            state[i].duty3List.forEach((e) => {
              const fd3Obj = data2Item.dutys.find((dty) => {
                const fd61 = e.options.find(
                  (fd61) => fd61.value == dty.dutyCode
                );
                return fd61 ? dty : null;
              });
              // console.log(fd3Obj);
              if (fd3Obj) {
                e.value = fd3Obj.dutyCode;
                e.isChecked = true;
                e.prem = fd3Obj.prem;
                e.amnt = fd3Obj.amnt;
              }
            });
          }
        }
      }
    }
    state = state.splice(1, 0);
  },
};
const actions = {
  /**
   * 险种信息校验
   * @param {*} param0
   * @param {*} payload
   * @returns
   */
  setValidate({ state, rootState, commit }, payload) {
    return new Promise((reslove, reject) => {
      let flag = true;
      let type = 2;
      let urlHash = window.location.hash;
      if (urlHash.indexOf("#/count") !== -1) {
        type = 1;
      }
      let content = validRules(state, payload, rootState, type);
      commit("SET_RISKSTATE", content);
      if (flag) {
        reslove("设置险种信息成功");
      } else {
        reject("险种校验失败");
      }
    });
  },
  /**
   * 设置险种信息
   * @param {*} context
   * @param {*} data
   */
  setRisks(context, data) {
    return new Promise((reslove, reject) => {
      // 1.校验险种规则
      context
        .dispatch("setValidate", data)
        .then((res) => {
          // 2.保费试算
          const zhuRisk = JSON.parse(JSON.stringify(context.state[0]));
          if (zhuRisk.noApiCount) {
            context
              .dispatch("noCountApi")
              .then((res) => {
                reslove("");
              })
              .catch((err) => {
                reject("计算错误");
              });
          } else {
            context
              .dispatch("getRateData")
              .then((res) => {
                reslove("");
              })
              .catch((err) => {
                reject("计算错误");
              });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    });
  },
  getRateData({ state, rootState, commit, rootGetters, dispatch }) {
    return new Promise((reslove, reject) => {
      // 共通方法获取请求参数
      let params = GetToRateparams(rootState, rootGetters);
      // console.log('getRateData---', params);
      params.workNum = rootState.insert.workNum;
      const insuType = rootGetters["page/isNetInsure"];
      if (insuType == "3") {
        params.mainRiskCode = rootGetters["insert/mainRiskCode"];
      }
      commit("updateLoad", true, { root: true });
      apiGetRate(params)
        .then(({ data }) => {
          commit("updateLoad", false, { root: true });
          if (data.code == 1) {
            let infos = {};
            if (insuType == "3") {
              infos = data;
              infos.productList[0].varietyCode = params.mainRiskCode;
            } else {
              infos = data.dataLists[0];
            }
            commit(
              "insert/UPDATE_PAYINFO",
              { totalPrem: infos.prem },
              { root: true }
            );
            commit("SET_RISKRATE", infos.productList);
            reslove("费率计算完成");
          } else {
            Dialog.alert({
              title: "提示",
              message: data.msg,
            }).then(() => {
              reject("计算出现异常");
            });
          }
        })
        .catch((err) => {
          commit("updateLoad", false, {
            root: true,
          });
          console.log(err);
        });
    });
  },
  noCountApi({ state, commit }) {
    return new Promise((reslove, reject) => {
      const zhuRisk = JSON.parse(JSON.stringify(state[0]));
      let retData = [
        {
          riskCode: zhuRisk.varietyCode,
        },
      ];
      commit("SET_RISKRATE", retData);
      commit(
        "insert/UPDATE_PAYINFO",
        { totalPrem: zhuRisk.prem },
        { root: true }
      );
      reslove("1");
    });
  },
  /**接口数据回显*/
  backRiskSetAnSheng({ state, dispatch, rootGetters }, list) {
    // console.log("backRiskSetAnSheng", list);
    if (state.length == 0) return;
    if (state[0].isNewUiConfig) return dispatch("resetAsNewUiApi", list);
    /**常规*/
    const zhuDuty = list.find((as) => Number(as.prem) > 0) || list[0];
    const mainCode = rootGetters["insert/mainRiskCode"];
    // 业绩列表进入回显
    const riskData = state[0];
    dispatch("setValidate", {
      varietyCode: mainCode,
      type: "prem",
      val: zhuDuty.prem || "0",
      noCacheData: true,
    });
    if (riskData.planCode) {
      dispatch("setValidate", {
        varietyCode: mainCode,
        type: "planCode",
        val: zhuDuty.riskCode,
        noCacheData: true,
      });
    }
    // 责任赋值
    if (riskData.apiCodes) {
      let duty2Arr = list.filter((e) => e.prem == null).map((d) => d.riskCode);
      dispatch("setValidate", {
        varietyCode: mainCode,
        type: "apiCodes",
        val: duty2Arr,
        noCacheData: true,
      });
    }
    // if (main1.insuYearStart) {
    //   dispatch("setValidate", {
    //     varietyCode: mainCode,
    //     type: "insuYearStart",
    //     val: main1.insuYearStart,
    //     noCacheData: true,
    //   });
    // }
    // if (main1.insuYearEnd) {
    //   dispatch("setValidate", {
    //     varietyCode: mainCode,
    //     type: "insuYearEnd",
    //     val: main1.insuYearEnd,
    //     noCacheData: true,
    //   });
    // }
  },
  resetAsNewUiApi({ state, dispatch, rootGetters }, list) {
    // console.log("resetAsNewUiApi---", list);
    const zhuItem = state[0];
    let keyObj = zhuItem.apiKeyFields;
    const len = zhuItem.insurePlanArr.length;
    let dutyArr = [];
    for (let i = 0; i < len; i++) {
      const item = zhuItem.insurePlanArr[i];
      const asb1 = item.codeList.find((ele) => {
        return list.find((as) => as.riskCode == ele.value) ? true : false;
      });
      if (asb1) {
        keyObj.planBigId = item.value;
        keyObj.planId = asb1.value;
      }
      dutyArr = item.fjbzKxArr || [];
    }
    // zympe
    const asb5 = zhuItem.zympeList.find((ele) => {
      return list.find((as) => ele.value.indexOf(as.riskCode) != -1)
        ? true
        : false;
    });
    if (asb5) {
      keyObj.zympe = asb5.value;
    }
    // dutys
    const len2 = dutyArr.length;
    let btnName = "",
      btnValue = "";
    if (len2 > 0) {
      for (let k = 0; k < len2; k++) {
        const item = dutyArr[k];
        const asb2 = item.radioList.find((ele) => {
          if (item.keyName == "mjz") {
            Object.keys(ele).map((key) => {
              const asb3 = list.find((as) => as.riskCode == ele[key]);
              if (asb3) {
                btnValue = asb3.riskCode;
                btnName = key;
              }
            });
            return btnValue ? true : false;
          } else {
            return list.find((as) => ele.value.indexOf(as.riskCode) != -1)
              ? true
              : false;
          }
        });
        // console.log(asb2);
        if (asb2) {
          if (item.keyName == "mjz") {
            keyObj[item.keyName] = btnValue;
            keyObj.mjztemp = btnName;
          } else {
            keyObj[item.keyName] = asb2.value;
          }
        } else {
          keyObj[item.keyName] = "no";
        }
      }
    }
    // exzl
    if (keyObj.exzl && keyObj.exzl != "no") {
      keyObj.ywtdyp = "";
    }
    //  ywtdyp
    if (keyObj.ywtdyp && keyObj.ywtdyp != "no") {
      keyObj.exzl = "";
    }
    // tdylqx
    if (keyObj.ywtdyp == "no" || !keyObj.ywtdyp) {
      keyObj.tdylqx = "";
    }
    const mainCode = rootGetters["insert/mainRiskCode"];
    dispatch("setValidate", {
      noCacheData: true,
      varietyCode: mainCode,
      type: "apiKeyFields",
      val: keyObj,
    });
    const zhuDuty = list.find((as) => Number(as.prem) > 0) || list[0];
    dispatch("setValidate", {
      varietyCode: mainCode,
      type: "prem",
      val: zhuDuty.prem || "0",
      noCacheData: true,
    });
  },
};
export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
};
